//
//  HDSellerObject.m
//  Food
//
//  Created by admin on 2018/8/9.
//  Copyright © 2018年 包月兴. All rights reserved.
//

#import "HDSellerObject.h"
#import "RLMObject+Extension.h"
#import <BmobSDK/Bmob.h>
#import "HDBmobFramework.h"
@implementation HDSellerObject
+(NSString *)primaryKey
{
    return @"objectId";
}


+(NSArray<NSString *> *)indexedProperties
{
    return @[@"updatedAt"];
}


+(void)insertDataWithBmobObjectLists:(NSArray<BmobObject *> *)lists complete:(void (^)(NSError * _Nullable))complete
{
    __block NSMutableArray *arr = [NSMutableArray array];
    [lists enumerateObjectsUsingBlock:^(BmobObject * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        HDSellerObject *sellerObject = [[HDSellerObject alloc] initWithBmobObject:obj];
        [arr addObject:sellerObject];
    }];
    
    if (arr.count > 0) {
        [self asynDataBlock:^{
            RLMRealm *realm = [RLMRealm defaultRealm];
            NSError *error;
            [realm transactionWithBlock:^{
                [realm addOrUpdateObjects:arr];
            } error:&error];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (complete) {
                    complete(error);
                }
            });
        }];
        return;
    }
    if (complete) {
        complete(nil);
    }
}


+(HDSellerObject *)sellerMsg
{
    return [HDSellerObject allObjects].firstObject;
}

+(NSDate *)getNewUpdatedAt
{
    RLMResults *results =[[HDSellerObject allObjects] sortedResultsUsingKeyPath:@"updatedAt" ascending:YES];
    if (results.count > 0) {
        HDSellerObject *object = results.lastObject;
        return object.updatedAt;
    }else
    {
        return nil;
    }
}

-(instancetype)initWithBmobObject:(BmobObject *)object
{
    if (self = [super init]) {
        _objectId = [object objectForKey:@"objectId"];
        _name = [object objectForKey:@"name"];
        _updatedAt = [BmobDataInstance.formatter dateFromString: [object objectForKey:@"updatedAt"]];
        _logoUrl = [object objectForKey:@"logo_url"];
        _address = [object objectForKey:@"address"];
        _startBusinessTime = [object objectForKey:@"business_start"];
        _endBusinessTime = [object objectForKey:@"business_end"];
        _telPhone = [object objectForKey:@"telephone"];
    }
    return self;
}
@end
